require 'jcode'

class StoryController < ApplicationController
  before_filter :login_required
  layout "main"
  
  def index
    list
    render :action=> "list"
  end
    
  def list
    @current = "story"
    @page_title = "All Stories"
    user = User.find_by_id(session[:user].id)
    @categories = user.categories
    stories = user.stories.find(:all,:order => "stories.created_at DESC")
    stories << user.borrowed_stories

    @story_pages, @stories = paginate_collection stories, :page => params[:page], :per_page => 5

  end
  
  def in_category
    @current = "story"
    user = User.find_by_id(session[:user].id)
    @category = user.categories.find_by_title(params[:id])
    @categories = user.categories
    @page_title = "Stories from the \"<i>#{@category.title}</i>\" Category"

    @story_pages, @stories = paginate_collection @category.stories.find(:all, :order => "created_at DESC"), 
                                                                    :page => params[:page], :per_page => 5
                                                            
    #@story_pages, @stories = paginate_collection Story.find(:all,
    #                                                        :select => "s.*,relationships.id AS relationship_id",
    #                                                        :joins => "as s join groupings g on g.story_id = s.id LEFT JOIN relationships ON (s.user_id = relationships.user_id_b AND relationships.initiator = #{session[:user].id}) OR (s.user_id = relationships.initiator AND relationships.user_id_b = #{session[:user].id}) AND relationships.validated = 1 " +
    #                                                                  "LEFT JOIN shared_stories ON s.id = shared_stories.story_id AND shared_stories.borrower_id = #{session[:user].id}",
    #                                                        :conditions => ["g.group_id = ?", params[:group_id]],
    #                                                        :order => "created_at DESC"), 
    #                                                        :page => params[:page], :per_page => 5
                                                            
  end
  
  def categories
    @current = "story"
    user = User.find_by_id(session[:user].id)
    @categories = user.categories.find(:all, :order => "categories.title")
    @story_id = params[:id]
    if !@story = user.stories.find(params[:id], :select => 'id, title')
      @story = user.shared_stories.find(params[:id], :select => 'id, title')
    end
    @page_title = "Select Categories for '#{@story.title}'"
    @story_categories = @story.categories

    if request.post?
    
      # Clear out any existing category <-> story
      # relationships.
      @story.categories.delete(@categories)
    
      # If any categories were selected then add
      # new category <-> story relationships here
      if params[:category_ids] then
        for category_id in params[:category_ids].uniq
          category = user.categories.find(category_id)
          @story.categories << category
        end
      end
      
      flash[:notice] ="#{@story.title} categories updated"
      
      if params[:relationship_id]
        redirect_to :controller => 'story', :action => 'view', :id => params[:id], :relationship_id => params[:relationship_id]
      else 
        redirect_to :controller => 'story', :action => 'view', :id => params[:id]
      end
    end 
  end
  
  def authored_by_other_users
    @current = "authored_by_other_users"
    user = User.find_by_id(session[:user].id)
    
    @page_title = "Authored by other users"
    
    @story_pages, @stories = paginate_collection user.borrowed_stories.find(:all,:order => "created_at DESC"), 
                                                                          :page => params[:page], :per_page => 5
                                                                          
    #@story_pages, @stories = paginate_collection Story.find(:all,
    #                                                        :select => "stories.*, relationships.id AS relationship_id",
    #                                                        :joins => "JOIN relationships ON (stories.user_id = relationships.user_id_b AND relationships.initiator = #{session[:user].id}) OR (stories.user_id = relationships.initiator AND relationships.user_id_b = #{session[:user].id}) " +
    #                                                                  "JOIN shared_stories ON stories.id = shared_stories.story_id AND shared_stories.borrower_id = #{session[:user].id} ",
    #                                                        :conditions => "relationships.validated",
    #                                                                      :order => "created_at DESC"), 
    #                                                                     :page => params[:page], :per_page => 5
                                                                          
                                                                          
  end
  
  def authored_by_user
      @current = "authored_by_other_users"
      user = User.find_by_id(session[:user].id)

      @owner = User.find(:first,
                         :select => "users.first_name, users.last_name, users.login, users.id",
                         :joins => "JOIN relationships ON (users.id = relationships.acceptor AND relationships.initiator = #{session[:user].id}) OR (users.id = relationships.initiator AND relationships.acceptor = #{session[:user].id})",
                         :conditions => ["relationships.validated AND users.id <> #{session[:user].id} AND relationships.id = ?", params[:relationship_id]]) 
                         
      @page_title = "All Stories Shared by #{@owner.first_name} #{@owner.last_name} (#{@owner.login})"
      @story_pages, @stories = paginate_collection Story.find(:all,
                                                              :select => "stories.*, users.*, relationships.id AS relationship_id",
                                                              :joins => "JOIN relationships ON (stories.user_id = relationships.acceptor AND relationships.initiator = #{session[:user].id}) OR (stories.user_id = relationships.initiator AND relationships.acceptor = #{session[:user].id}) " +
                                                                        "JOIN shared_stories ON stories.id = shared_stories.story_id AND shared_stories.borrower_id = #{session[:user].id} ",
                                                              :conditions => ["relationships.validated AND relationships.id = ?",params[:relationship_id]],
                                                                            :order => "created_at DESC"), 
                                                                            :page => params[:page], :per_page => 5
    
  end
  
  def view
    @current = "story"
    
    if params[:relationship_id]
      @owner = User.find(:first,
                       :select => "users.first_name, users.last_name, users.login, users.id",
                       :joins => "JOIN relationships ON (users.id = relationships.acceptor AND relationships.initiator = #{session[:user].id}) OR (users.id = relationships.initiator AND relationships.acceptor = #{session[:user].id})",
                       :conditions => ["relationships.validated AND users.id <> #{session[:user].id} AND relationships.id = ?", params[:relationship_id]]) 
      @story = Story.find(:first,
                          :select => "stories.*, relationships.id AS relationship_id",
                          :joins => "JOIN relationships ON (stories.user_id = relationships.acceptor AND relationships.initiator = #{session[:user].id}) OR (stories.user_id = relationships.initiator AND relationships.acceptor = #{session[:user].id}) " +
                                    "JOIN shared_stories ON stories.id = shared_stories.story_id AND shared_stories.borrower_id = #{session[:user].id} ",
                          :conditions => ["relationships.validated AND relationships.id = ? AND stories.id = ?",params[:relationship_id], params[:id]],
                                        :order => "created_at DESC")    
    else 
      @story = Story.find_by_id(params[:id],
                                    :conditions => "user_id = #{session[:user].id}",
                                    :order => "created_at DESC")
    end
    
    if !@story
      flash[:notice] ="Story is no longer available."
      redirect_to :controller => 'story'
    else
      @page_title = "Story: '#{@story.title}'"
      
      if @owner
        @page_title += " Shared by #{@owner.first_name} #{@owner.last_name} (#{@owner.login})"
      end
    end
    
    @categories = @story.categories
    
  end
  
  def new
    @current = "story"
    @page_title = "Create new story"
    @story = Story.new(params[:story])
    @story.user_id = session[:user].id
    
    if request.post? and @story.save      
      # add the new words
      @story.words = parse_words(@story.body << " " << @story.title)
      flash[:notice] ="Story '#{@story.title}' was added"
      redirect_to :controller => 'story'
    end 
  end
  
  def edit
    @page_title = "Create new story"
    id = params[:id]
    user = User.find_by_id(session[:user].id)
    @story = user.stories.find(id,:order => "stories.created_at DESC")
    
    if request.post?
      @story.update_attributes(params[:story])
      
      # clear old words
      @story.words.each do |word| @story.words.delete(word) end
      
      # add the new words
      @story.words = parse_words(@story.body << " " << @story.title)
      
      flash[:notice] ="Story '#{@story.title}' was updated"
      redirect_to :action => 'index'  
    end
      
  end
  
  def delete
  
    id = params[:id]
    user = User.find_by_id(session[:user].id)
    story = user.stories.find(id)
    story_title = story.title
    
    story.words.each do |word| 
      story.words.delete(word)
    end

    story.destroy
    
    flash[:notice] = "Story \"#{story_title}\" deleted"
    redirect_to :action => 'index'
    
  end

  private 
  
  def parse_words(text)
  
    # Change the parser config in environment.rb

    if text.mbchar?
      if Parser::PARSER == "lib" then
        require Parser::PARSER_PATH
        @words = Kakasi.kakasi(Parser::PARSER_FLAGS,text.gsub!(Parser::EXCLUDED_CHARACTERS, " ").toeuc).toutf8.split(" ").uniq
      else
        IO.popen(Parser::PARSER_PATH + Parser::PARSER_FLAGS, 'r+') do |io| 
         io.puts text.gsub!(Parser::EXCLUDED_CHARACTERS, " ").toeuc
         io.close_write
         @words = io.read.toutf8.split(" ").uniq
        end
      end
    else
      @words = text.split(" ").uniq
    end
    
    # Set an array of words to return to the story
    @story_words = []
    
    @words.each do |word|
      unless @word = Word.find_by_word(word)   
        @word = Word.create(:word => word)
      end
      
      @story_words << @word
      
    end
    
    return @story_words
    
  end
 
end
